package com.bingxue.edu.management.system.controller;

import com.bingxue.edu.common.enums.CommonStatusEnum;
import com.bingxue.edu.framework.common.model.Response;
import com.bingxue.edu.framework.common.model.SortQuery;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.framework.enums.Dict;
import com.bingxue.edu.framework.enums.DictEnum;
import com.bingxue.edu.framework.enums.DictEnums;
import com.bingxue.edu.framework.mybatis.query.QueryBuilder;
import com.bingxue.edu.framework.security.ApiResource;
import com.bingxue.edu.management.system.model.entity.DictItem;
import com.bingxue.edu.management.system.model.query.DictItemQuery;
import com.bingxue.edu.management.system.model.query.DictQuery;
import com.bingxue.edu.management.system.model.req.DictCreateReq;
import com.bingxue.edu.management.system.model.req.DictItemCreateReq;
import com.bingxue.edu.management.system.model.req.DictItemSortReq;
import com.bingxue.edu.management.system.model.req.DictItemUpdateReq;
import com.bingxue.edu.management.system.model.req.DictUpdateReq;
import com.bingxue.edu.management.system.model.resp.DictDetailResp;
import com.bingxue.edu.management.system.model.resp.DictItemDetail;
import com.bingxue.edu.management.system.model.resp.DictItemResp;
import com.bingxue.edu.management.system.model.resp.DictResp;
import com.bingxue.edu.management.system.service.DictItemService;
import com.bingxue.edu.management.system.service.DictService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import static com.bingxue.edu.management.system.model.entity.table.DictItemTableDef.DICT_ITEM;

/**
 * 1. xunuo分支合并dev分支代码后提交到远端的xunuo分支，然后在远端进行合并到dev  1
 * 2. 先拉取远端dev分支变更，然后从本地dev分支合并本地的xunuo分支，然后提交到远端dev分支
 * 字典接口
 *
 * @author xunuo
 * @since 2024/07/23 10:37
 */
@SuppressWarnings("rawtypes")
@Tag(name = "字典接口")
@RestController
@RequestMapping("/system/dict")
@RequiredArgsConstructor
public class DictController {

    private final DictService dictService;
    private final DictItemService dictItemService;

    @Operation(summary = "查询枚举字典列表")
    @ApiResource("system:dict:manage")
    @GetMapping("/list/enum")
    public Response<List<DictResp>> listEnumDict() {
        Set<Class<?>> enumClassSet = DictEnums.getEnumClassSet();
        List<DictResp> list = enumClassSet.stream().map(enumClass -> {
            DictResp dictResp = new DictResp();
            dictResp.setId(enumClass.getSimpleName());
            dictResp.setCode(enumClass.getSimpleName());
            dictResp.setReserved(true);
            Dict annotation = enumClass.getAnnotation(Dict.class);
            if (annotation != null) {
                dictResp.setName(annotation.value());
            }
            return dictResp;
        }).toList();
        return Response.success(list);
    }

    @Operation(summary = "查询自定义字典列表")
    @ApiResource("system:dict:manage")
    @GetMapping("/list")
    public Response<List<DictResp>> list(DictQuery query, SortQuery sortQuery) {
        QueryWrapper queryWrapper = QueryBuilder.build(query, sortQuery);
        List<DictResp> list = dictService.listAs(queryWrapper, DictResp.class);
        return Response.success(list);
    }

    @Operation(summary = "查询详情")
    @ApiResource("system:dict:manage")
    @GetMapping("/detail/{id}")
    public Response<DictDetailResp> detail(@PathVariable String id) {
        DictDetailResp detail = dictService.getMapper().selectOneWithRelationsByIdAs(id, DictDetailResp.class);
        return Response.success(detail);
    }

    @Operation(summary = "创建数据")
    @ApiResource("system:dict:manage")
    @PostMapping("/create")
    public Response<Boolean> create(@RequestBody @Validated DictCreateReq req) {
        boolean result = dictService.addDict(req);
        return Response.success(result);
    }

    @Operation(summary = "更新数据")
    @ApiResource("system:dict:manage")
    @PostMapping("/update/{id}")
    public Response<Void> update(@RequestBody @Validated DictUpdateReq req, @PathVariable String id) {
        dictService.updateDict(req, id);
        return Response.success();

    }

    @Operation(summary = "删除数据")
    @ApiResource("system:dict:manage")
    @PostMapping("/delete/{ids}")
    public Response<Void> delete(@PathVariable List<String> ids) {
        dictService.deleteDict(ids);
        return Response.success();
    }


    @Operation(summary = "查询字典项详情")
    @ApiResource("system:dict:manage")
    @GetMapping("/item/detail/{id}")
    public Response<DictItemDetail> itemDetail(@PathVariable String id) {
        DictItemDetail detail = dictItemService.getMapper().selectOneWithRelationsByIdAs(id, DictItemDetail.class);
        return Response.success(detail);
    }

    @Operation(summary = "创建字典项")
    @ApiResource("system:dict:manage")
    @PostMapping("/item/create")
    public Response<Boolean> createItem(@RequestBody @Validated DictItemCreateReq req) {
        Boolean result = dictItemService.addDictItem(req);
        return Response.success(result);

    }

    @Operation(summary = "更新字典项")
    @ApiResource("system:dict:manage")
    @PostMapping("/item/update/{id}")
    public Response<Void> updateItem(@RequestBody @Validated DictItemUpdateReq req, @PathVariable String id) {
        dictItemService.updateDictItem(req, id);
        return Response.success();
    }

    @Operation(summary = "删除字典项")
    @ApiResource("system:dict:manage")
    @PostMapping("/item/delete/{ids}")
    public Response<Void> deleteItem(@PathVariable List<String> ids) {
        dictItemService.deleteDictItem(ids);
        return Response.success();
    }

    @Operation(summary = "排序字典项")
    @ApiResource("system:dict:manage")
    @PostMapping("/item/sort")
    public Response<Void> sortItems(@Validated @RequestBody DictItemSortReq req) {
        dictItemService.sortDictItems(req);
        return Response.success();
    }


    @Operation(summary = "查询字典项列表")
    @ApiResource("system:dict:manage")
    @GetMapping("/item/list")
    public Response<List<DictItemResp>> itemList(DictItemQuery query) {
        String dictId = query.getDictId();
        CommonStatusEnum status = query.getStatus();
        ValidationUtils.throwIfNull(query.getDictId(),"参数传递错误");
        List<DictItemResp> result;
        //系统字典
        for (Class<?> enumClass : DictEnums.getEnumClassSet()) {
            if (enumClass.getSimpleName().equals(dictId)) {
                Object[] enumConstants = enumClass.getEnumConstants();
                result = Arrays.stream(enumConstants).map(e -> {
                    DictEnum item = (DictEnum) e;
                    DictItemResp dictItem = new DictItemResp();
                    dictItem.setId(item.getValue().toString());
                    dictItem.setDictId(dictId);
                    dictItem.setLabel(item.getLabel());
                    dictItem.setValue(item.getValue().toString());
                    dictItem.setColor(item.getColor());
                    dictItem.setStatus(CommonStatusEnum.of(!item.isDisabled()));
                    dictItem.setSort(0);
                    return dictItem;
                }).toList();
                return Response.success(result);
            }
        }
        //自定义字典
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(DICT_ITEM.ALL_COLUMNS)
                .where(DICT_ITEM.DICT_ID.eq(dictId))
                .orderBy(DictItem::getSort).asc();
        if (query.getStatus() != null) {
            queryWrapper.and(DICT_ITEM.STATUS.eq(status));
        }
        result = dictItemService.listAs(queryWrapper, DictItemResp.class);
        return Response.success(result);
    }

    @Operation(summary = "根据code查询id")
    @ApiResource("system:dict:manage")
    @GetMapping("/item/get-id-by-code/{code}")
    public Response<String> getIdByCode(@PathVariable String code) {
        com.bingxue.edu.management.system.model.entity.Dict entityByCode = dictService.getEntityByCode(code);
        return Response.success(entityByCode.getId());
    }

}
